﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

namespace TodayWhoModel
{
    class DatabaseHelper
    {
        public static SqlDataReader ExecuteSelectSql(SqlCommand cmd)
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            SqlDataReader reader;
            try
            {
                conn.Open();
                cmd.Connection = conn;
                reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            }
            catch
            {
                reader = null;
            }
            return reader;
        }
        public static int ExecuteInsertSqlWithIdentity(SqlCommand cmd)
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
            }
            catch
            {
            }
            if (!(cmd.Parameters[0].Value == (object)DBNull.Value))
            {
                return Int32.Parse(cmd.Parameters[0].Value.ToString()); // output parameter
            }
            else
            {
                return 0;
            }

        }

        public static bool ExecuteNonQuerySqlWithoutIdentity(SqlCommand cmd)
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                conn.Open();
                cmd.Connection = conn;
                int affeted = cmd.ExecuteNonQuery();
                if (affeted == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public static int ExecuteScalar(SqlCommand cmd)
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            int count = 0;
            try
            {
                conn.Open();
                cmd.Connection = conn;
                count = (Int32)cmd.ExecuteScalar();
            }
            catch
            {

            }
            return count;

        }
    }
}
